package com.ruoyi.project.app.controller;

import ai.advance.cmp.api.client.bean.ResponseBean;
import ai.advance.cmp.api.client.bean.dto.*;
import ai.advance.cmp.api.client.bean.dto.query.OrderQueryDTO;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.app.util.OrderCoderUtil;
import com.ruoyi.project.app.util.XResult;
import com.ruoyi.project.beautyflower.order.domain.Order;
import com.ruoyi.project.beautyflower.order.service.OrderServiceImpl;
import com.ruoyi.project.beautyflower.paymentHistory.domain.PaymentHistory;
import com.ruoyi.project.beautyflower.paymentHistory.mapper.PaymentHistoryMapper;
import com.ruoyi.project.beautyflower.paymentHistory.service.PaymentHistoryServiceImpl;
import com.ruoyi.project.beautyflower.repaymentPlan.domain.RepaymentPlan;
import com.ruoyi.project.beautyflower.repaymentPlan.service.RepaymentPlanServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 第三方回调接口
 *
 * @author lxs
 * @date 2018-09-28
 */
@Controller
@RequestMapping("/front/bfcallback")
public class BfCallbackController {

    @Autowired
    private OrderServiceImpl orderService;//订单service

    @Autowired
    private RepaymentPlanServiceImpl repaymentPlanService;//还款计划

    @Autowired
    private PaymentHistoryServiceImpl paymentHistoryService;//还款记录

    /**
     * 修改订单状态REPAYMENTS
     * @param disburseResultDTO
     * @return
     */
    @PostMapping("/updateOrderBystatus")
    @ResponseBody
    public ResponseBean updateOrderBystatus(@RequestBody DisburseResultDTO disburseResultDTO)  {
        int count=0;
        Order order=orderService.selectOrderByListOrderNumber(disburseResultDTO.getOrderId());
        if(order!=null){
            if(disburseResultDTO.getStatus().equals("SUCCESS")){
//                order.setStatus("ONGOING");
                order.setStatus("REPAYMENTS");
            }else{
                order.setStatus("DISBURSEMENT_FAILED");
            }
            count=orderService.updateOrder(order);
        }
        ResponseBean responseBean=new ResponseBean();
        if(count>0){
            responseBean.setCode("SUCCESS");
            responseBean.setMessage("修改成功");
        }else{
            responseBean.setCode("ERROR");
            responseBean.setMessage("修改失败");
        }
        return responseBean;
    }


    /**
     * 创建还款计划
     * @param repaymentScheduleCreateDTO
     * @return
     */
    @PostMapping("/insertRepaymentPlan")
    @ResponseBody
    public ResponseBean insertRepaymentPlan(@RequestBody RepaymentScheduleCreateDTO repaymentScheduleCreateDTO)  {
        int sum=0;
        List<InstallmentDTO> details=repaymentScheduleCreateDTO.getDetails();
        if(details!=null&&details.size()>0){
            for (InstallmentDTO detail : details) {
                RepaymentPlan repaymentPlan=new RepaymentPlan();
                repaymentPlan.setDueAmount(Double.parseDouble(detail.getDueAmount()+""));
                repaymentPlan.setDueDate(detail.getDueDate());
                repaymentPlan.setDueInterestAmount(Double.parseDouble(detail.getDueInterestAmount()+""));
                repaymentPlan.setFee(detail.getFee()+"");
                repaymentPlan.setDuePrincipalAmount(Double.valueOf(detail.getDuePrincipalAmount()+""));
                repaymentPlan.setInstallmentNo(detail.getInstallmentNo()+"");
                repaymentPlan.setInterestStartDate(detail.getInterestStartDate());
                repaymentPlan.setInterestEndDate(detail.getInterestEndDate());
                repaymentPlan.setOrderNumber(repaymentScheduleCreateDTO.getOrderId());
                repaymentPlan.setStatus("ONGOING");
                int count=repaymentPlanService.insertRepaymentPlan(repaymentPlan);
                sum=sum+count;
            }
        }
        ResponseBean responseBean=new ResponseBean();
        if(details.size()==sum){
//            return new XResult("创建还款计划成功",sum);
            responseBean.setCode("SUCCESS");
            responseBean.setMessage("创建还款计划成功");
        }else{
//            return new XResult("创建还款计划失败",sum);
            responseBean.setCode("ERROR");
            responseBean.setMessage("创建还款计划失败");
        }
        System.out.println(responseBean.toString());
        return responseBean;
    }


    /**
     * 还款状态更新回调
     * @return
     */
    @PostMapping("/updateRepaymentPlan")
    @ResponseBody
    public ResponseBean updateRepaymentPlan(@RequestBody NotifyRepaymentResultDTO notifyRepaymentResultDTO){
        ResponseBean responseBean=new ResponseBean();
        List<PaymentHistory> paymentHistoryList=paymentHistoryService.findPaymentHistoryListBypaymentNo(notifyRepaymentResultDTO.getRepaymentActionId());

        if(paymentHistoryList!=null&&paymentHistoryList.size()>0){
            for (PaymentHistory paymentHistory : paymentHistoryList) {
                RepaymentPlan repaymentPlan=repaymentPlanService.selectOrderByListByOrderNumberAndinstallmentNo(paymentHistory.getOrderId(),paymentHistory.getInstallmentNo());
                if(repaymentPlan!=null){
                    if(notifyRepaymentResultDTO.getStatus().equals("SUCCESS")){
                        try {
                            repaymentPlan.setStatus("REPAID");
                            repaymentPlanService.updateRepaymentPlan(repaymentPlan);
                            RepaymentPlan repaymentPlan1=new RepaymentPlan();
                            repaymentPlan1.setStatus("REPAID");
                            repaymentPlan1.setOrderNumber(paymentHistory.getOrderId());
                            List<RepaymentPlan> repaymentPlanList=repaymentPlanService.selectRepaymentPlanList(repaymentPlan1);
                            responseBean.setCode("SUCCESS");
                            responseBean.setMessage("修改还款计划状态成功");
                            Order order=orderService.selectOrderByListOrderNumber(paymentHistory.getOrderId());
                            if(order!=null&&!order.getStatus().equals("ONGOING")){
                                order.setStatus("ONGOING");
                                orderService.updateOrder(order);
                            }
                            if(order!=null){
//                                if(order.getOrderPeriods()==Integer.valueOf(repaymentPlan.getInstallmentNo())){
                                    if(repaymentPlanList!=null&&repaymentPlanList.size()>0){
                                        if(order.getOrderPeriods()==repaymentPlanList.size()){
                                            order.setStatus("COMPLETED");
                                            orderService.updateOrder(order);
                                        }
                                    }
//                                }
                            }
                        } catch (Exception e) {
                            responseBean.setCode("ERROR");
                            responseBean.setMessage("参数异常");
                        }
                    }
                }
                paymentHistory.setStatus(notifyRepaymentResultDTO.getStatus());
                try {
                    paymentHistoryService.updatePaymentHistory(paymentHistory);
                    responseBean.setCode("SUCCESS");
                    responseBean.setMessage("修改还款记录状态成功");
                } catch (Exception e) {
                    responseBean.setCode("ERROR");
                    responseBean.setMessage("修改状态失败，参数异常");
                }
            }
        }
        List<UnpaidInstallmentChangedDTO> unpaidInstallmentChangedList=notifyRepaymentResultDTO.getUnpaidInstallmentChangedList();
        if(unpaidInstallmentChangedList!=null&&unpaidInstallmentChangedList.size()>0){
            for (UnpaidInstallmentChangedDTO unpaidInstallmentChangedDTO : unpaidInstallmentChangedList) {
                String orderId=unpaidInstallmentChangedDTO.getOrderId();
                List<UnpaidInstallmentChangedDetailDTO> unpaidInstallmentChangedDetailDTOList=unpaidInstallmentChangedDTO.getUnpaidInstallmentChangedDetailList();
                if(unpaidInstallmentChangedDetailDTOList!=null&&unpaidInstallmentChangedDetailDTOList.size()>0){
                    for (UnpaidInstallmentChangedDetailDTO unpaidInstallmentChangedDetailDTO : unpaidInstallmentChangedDetailDTOList) {
                        RepaymentPlan  repaymentPlan=repaymentPlanService.selectOrderByListByOrderNumberAndinstallmentNo(orderId,unpaidInstallmentChangedDetailDTO.getInstallmentNo()+"");
                        repaymentPlan.setDueDate(unpaidInstallmentChangedDetailDTO.getDueDate());
                        repaymentPlan.setInterestStartDate(unpaidInstallmentChangedDetailDTO.getInterestStartDate());
                        repaymentPlan.setInterestEndDate(unpaidInstallmentChangedDetailDTO.getInterestEndDate());
                        try {
                            repaymentPlanService.updateRepaymentPlan(repaymentPlan);
                            responseBean.setCode("SUCCESS");
                            responseBean.setMessage("更新成功");
                        } catch (Exception e) {
                            responseBean.setCode("ERROR");
                            responseBean.setMessage("更新还款计划数失败 ，参数异常");
                        }
                    }

                }



            }
        }
        return responseBean;
    }

    /**
     * 自动还款回调
     * @return
     */
    @PostMapping("/automaticDeduction")
    @ResponseBody
    public ResponseBean automaticDeduction(@RequestBody DeductionResultDTO deductionResultDTO){
        RepaymentPlan  repaymentPlan=repaymentPlanService.selectOrderByListByOrderNumberAndinstallmentNo(deductionResultDTO.getOrderId(),deductionResultDTO.getInstallmentNo()+"");
        String contractNo= OrderCoderUtil.toCode(Long.parseLong(deductionResultDTO.getUserId()+""));//某次通知还款动作的惟一标识
        ResponseBean responseBean=new ResponseBean();
        if(repaymentPlan!=null){
                PaymentHistory paymentHistory=new PaymentHistory();
                paymentHistory.setOrderId(deductionResultDTO.getOrderId());//订单id
                paymentHistory.setInstallmentNo(deductionResultDTO.getInstallmentNo()+"");//还款分期号
                paymentHistory.setDuePrincipalAmount(deductionResultDTO.getPrincipalAmount());//应还款本金
                paymentHistory.setRepaymentInterestAmount(deductionResultDTO.getInterestAmount());//应还款利息
                paymentHistory.setRepaymentPrincipalAmount(deductionResultDTO.getPrincipalAmount());//实际还款本金
                paymentHistory.setBeOverdue(deductionResultDTO.getDefaultFine());//罚息
                paymentHistory.setStatus(deductionResultDTO.getStatus());
                paymentHistory.setRepaymentTime(DateUtils.getTime());
                paymentHistory.setMemberId(Integer.parseInt(deductionResultDTO.getUserId()));
                paymentHistory.setBankCardNumber(deductionResultDTO.getBankCardNumber());
                paymentHistory.setBankName(deductionResultDTO.getBankName());
                paymentHistory.setPaymentNo(contractNo);
                paymentHistoryService.insertPaymentHistory(paymentHistory);
                if(deductionResultDTO.getStatus().equals("SUCCESS")){
                    repaymentPlan.setStatus("SUCCESS");
                    repaymentPlanService.updateRepaymentPlan(repaymentPlan);
                    Order order=orderService.selectOrderByListOrderNumber(deductionResultDTO.getOrderId());
                    if(order.getOrderPeriods()==Integer.valueOf(deductionResultDTO.getInstallmentNo())){
                        order.setStatus("COMPLETED");
                        orderService.updateOrder(order);
                    }
                }
            }
        responseBean.setCode("SUCCESS");
        responseBean.setMessage("OK");
        return responseBean;
    }


}
